<!--
 * @Description: 灌溉控制
-->
<template>
  <BaseMainSlot :show-tab="false" :show-search-box="false" :show-btn-box="false">
    <!-- <template v-slot:btn-box>
      <ActionBar
        :page-no="102"
        :has-edit="false"
        :has-save="false"
        :has-add="false"
        :has-del="false"
        :has-cancel="false"
      />
    </template> -->
    <template v-slot:table-box>
      <template v-if="!showMap">
        <div v-if="showControl" class="irrigation-box">
          <div class="toggle-box">
            <div class="toggle-btn" @click="toggleMap()">切换地图查看</div>
          </div>
          <div class="control-head">
            <div class="control-data">
              <div class="data-one" title="点击可查看详情" @click="toControlOper(1)">
                <div class="num-title">总开启数量</div>
                <div class="num">{{ numObj.openTotal || 0 }}</div>
              </div>
              <div class="data-one" title="点击可查看详情" @click="toControlOper(0)">
                <div class="num-title">总关闭数量：</div>
                <div class="num">{{ numObj.closeTotal || 0 }}</div>
              </div>
              <div class="data-one" title="点击可查看详情" @click="toControlOper(1, true)">
                <div class="num-title">当前区域开启数：</div>
                <div class="num">{{ numObj.open || 0 }}</div>
              </div>
              <div class="data-one" title="点击可查看详情" @click="toControlOper(0, true)">
                <div class="num-title">当前区域关闭数：</div>
                <div class="num">{{ numObj.close || 0 }}</div>
              </div>
            </div>
            <div class="area-mode">
              <div class="control-area">
                <div class="label">请选择控制区域：</div>
                <div class="control-content">
                  <div
                    class="area-one"
                    v-for="item,i in facilityList"
                    :key="item.facilityNo"
                    :class="{ 'active': item.facilityNo == defaultFacilityNO }"
                    @click="viewFacility(item, i)"
                  >
                    {{ item.facilityName }}
                  </div>
                </div>
              </div>
              <div class="control-mode">
                <div class="label">控制模式选择：</div>
                <div class="mode-content">
                  <div
                    class="mode-one"
                    v-for="item,i in modeList"
                    :class="{ 'active': i == selectIndex }"
                    @click="checkMode(i)"
                  >
                    {{ item }}
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="right" v-loading="loading">
            <div class="irrigation-one" :class="{ 'single': ![0, 1].includes(selectIndex) }">
              <div class="irrigation-title" v-if="[0, 1].includes(selectIndex)">
                <div class="group-btn">
                  <template v-if="selectIndex == 0">
                    <div class="btn-one" v-for="item,index in (tableData.dataTypeMsgs || [])" :key="index">
                      设备总控制：
                      <div
                        v-for="(
                          kaiguanitem, kaiguanindex
                        ) in handeltwo(item.enumListType)"
                        :key="kaiguanindex"
                        class="contro-two-zcon"
                        :class="{ 'close': kaiguanitem.name.includes('关') }"
                        @click="
                          controlequpmentone(
                            item.dataTypeId,
                            kaiguanitem.value,
                            defaultFacilityNO,
                          )
                        "
                      >
                        {{ kaiguanitem.name }}
                      </div>
                    </div>
                  </template>
                  <div class="btn-one" v-if="selectIndex == 1">
                    批量控制：
                    <div class="contro-two-zcon close" @click="controlEqupmentBatch(0)">
                      关
                    </div>
                    <div class="contro-two-zcon" @click="controlEqupmentBatch(1)">
                      开
                    </div>
                  </div>
                </div>
                <div v-show="showTaskBtn" class="task-btn" @click="showTask">
                  控制进度
                </div>
              </div>
              <div class="content">
                <el-checkbox-group v-model="checkGroupList">
                  <div class="group" v-for="ite in (tableData.groups || [])" :key="ite.groupNo">
                    <div class="group-title" v-if="selectIndex == 1">
                      <el-checkbox :label="ite.groupNo">{{ ite.groupName }}</el-checkbox>
                    </div>
                    <div class="group-title" v-else>
                      {{ ite.groupName }}
                    </div>
                    <div class="control-box">
                      <div class="zh-contro" v-for="item,index in (ite.dataItems || [])" :key="index">
                        <div class="contro-one">
                          <div class="contro-one-title">{{ item.dataItemName }}</div>
                          <div
                            class="contro-one-stau"
                            :style="{ color: getequipmentStyle(item.nowstau) }"
                          >{{ item.nowstau }}</div>
                        </div>
                        <div
                          class="contro-two"
                          v-if="selectIndex == 2"
                        >
                          <div
                            v-for="(
                              kaiguanitem, kaiguanindex
                            ) in handeltwo(item.enumListType)"
                            :key="kaiguanindex"
                            class="contro-two-zcon"
                            :class="{ 'close': kaiguanitem.name.includes('关') }"
                            @click="
                              controlequpmentone(
                                item.dataItemId,
                                kaiguanitem.value,
                              )
                            "
                          >
                            {{ kaiguanitem.name }}
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </el-checkbox-group>
                <div class="nodata" v-if="(tableData.groups || []).length == 0">
                  暂无数据
                </div>
              </div>
            </div>
          </div>
        </div>

        <template v-else>
          <butterfly :operationList="operationList" :facilityName="operFacilityName"
            @back="back" @openCode="openCode" />
        </template>
      </template>

      <div v-if="showMap" class="map-box">
        <template v-if="!showMapControl">
          <div class="toggle-box">
            <div class="toggle-btn" @click="toggleMap()">返回</div>
          </div>
          <baidu-map
            class="map"
            :center="center"
            :zoom="zoom"
            :scroll-wheel-zoom="true"
            map-type="BMAP_HYBRID_MAP"
          >
            <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT" />
            <BmlMarkerClusterer :average-center="true">
              <bm-marker
                v-for="(item, index) in groupLngLatArr"
                :key="index + 9999999999"
                :position="{
                  lng: item.center.lng - 0.000003,
                  lat: item.center.lat - 0.000043,
                }"
                :dragging="false"
              >
                <bm-label
                  :content="item[0].title.facilityName"
                  :label-style="labelStyle"
                  :offset="{ width: -5, height: 15 }"
                  @click="infoMultipleOpen(item)"
                />
              </bm-marker>
            </BmlMarkerClusterer>
            <div v-for="(item, index) in groupLngLatArr" :key="index">
              <bm-polygon
                :path="item"
                stroke-color="#03F5EC"
                fill-color="#00fff6"
                :stroke-opacity="1"
                :fill-opacity="0.2"
                :stroke-weight="3"
                @click="infoMultipleOpen(item)"
              />
            </div>
          </baidu-map>
        </template>
        <!-- <template v-else>
          <butterflyArea :operationList="mapOperationList" :facilityName="mapFacilityName"
            @back="backMap" @openCode="openCode" />
        </template> -->
      </div>
      <!-- 开关验证码弹框 -->
      <el-dialog
        title="输入验证码"
        :visible.sync="yanzhengcodeview"
        width="30% !important"
        class="yanzheng"
      >
        <div class="dig-yanzhencode">
          <div>
            <img :src="nowcodeimg" />
            <div
              class="changecodeimg"
              @click="openyanzhencode()"
            >看不清换一张</div>
          </div>
          <el-input
            v-model="inputCode"
            placeholder="请输入验证码"
          />
        </div>
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button
            type="success"
            @click="yanzhengcodeview = false"
          >取消</el-button>
          <el-button
            type="primary"
            @click="yanzhengcode()"
          >确认执行</el-button>
        </span>
      </el-dialog>
      <!-- 控制进度弹框 -->
      <!-- :title="`控制进度(${nowcontrolmessage.zhkey == 0 ? '关闭' : '开启'})`" -->
      <el-dialog
        class="scheduleForm"
        title="控制进度"
        :visible.sync="dialogVisible"
        :show-close="true"
        :modal="true"
        width="40% !important"
      >
        <div class="schedule">
          <div class="progress-box">
            <span>控制进度提示：</span>
            <el-progress class="progress" :stroke-width="10" :percentage="percentage"
              color="#2CD4C5" define-back-color="#dde"></el-progress>
          </div>
          <div class="content" ref="scrollview">
            <div v-loading="!item.controled" class="schedule-one" v-for="item,index in scheduleList" :key="item.dataItemId">
              <div class="line">{{ item.dataItemName }}</div>
              <div class="msg line" v-if="!item.controled">{{ item.status || '准备中' }}</div>
              <div class="line" :class="{'green': item.msg == '控制成功', 'red': item.msg != '控制成功'}" v-else>
                {{ item.msg }}
              </div>
              <div v-if="item.status && item.status != '待执行' && !item.controled" style="margin-top: 12px;">
                <el-progress :percentage="percentageObj[item.dataItemId]" :show-text="false"
                  color="#2CD4C5" define-back-color="#dde"></el-progress>
              </div>
            </div>
          </div>
        </div>
        <!-- v-if="showScheduleClose" -->
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button
            type="primary"
            @click="dialogVisible = false"
          >关闭</el-button>
        </span>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
// import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import irrigationApi from "@/api/digital-production/material-link-monitoring/irrigation-control";
import facilityApi from "@/api/basic-info-manage/facility-group-management";
import SearchForm from "@/components/searchForm";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot.vue";
import butterfly from "./component/butterfly";
import { BmlMarkerClusterer } from "vue-baidu-map";
import divideInfoManage from "@/api/digital-operation/land-manage/divide-manage";
import { getToken } from "@/utils/auth";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";
import Axios from "axios";
export default {
  // eslint-disable-next-line vue/name-property-casing
  name: "dataManagement",
  components: { Pagination, BaseMainSlot, SearchForm, butterfly, BmlMarkerClusterer },
  mixins: [mymixin],
  data() {
    return {
      loading: false,
      facilityList: [],
      numObj: {},
      operationList: [],
      showControl: true,
      operFacilityName: '',
      modeList: ['按管道总控', '按阀门组控制', '按单个阀门控制', '查看所有阀门状态'],
      selectIndex: 0,
      formConfig: [
        {
          label: "设施分组名称",
          prop: "facilityGroupName",
          type: "select",
          options: [],
          optionKey: { label: "facilityGroupName", value: "facilityGroupName" },
        },
      ],
      searchlist: {},
      tableData: [],
      facilityName: '',
      checkGroupList: [],
      allData: [],
      // 验证码弹框
      yanzhengcodeview: false,
      inputCode: '',
      nowcodeimg: '',
      dialogVisible: false,
      percentage: 0,
      scheduleList: [],
      showScheduleClose: false,
      total: 0,
      co: 0,
      groupObj: {},
      nowcontrolmessage: {},
      showTaskBtn: false,
      // 所有设备的待执行计时器
      intervalObj: {},
      percentageObj: {},
      // 地图相关值
      showMap: false,
      groupLngLatArr: [],
      center: { lng: 120.230648, lat: 30.811543 },
      zoom: 17,
      labelStyle: {
        color: "#fffff0",
        fontSize: "12px",
        borderRadius: "8px",
        border: "none",
        backgroundColor: "#00a1c2",
        padding: "3px",
        opacity: ".8",
        letterSpacing: "2px",
        transform: "translateX(-32%)"
      },
      showMapControl: false,
      mapOperationList: [],
      mapFacilityName: '',
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    }),
  },
  watch: {},
  created () {
    this.FacilityPointList()
    this.getfacilityList()
  },
  mounted () {
    this.init()
  },
  methods: {
    // 查询正在运行存在的任务
    loadTask() {
      for (let key in this.intervalObj) {
        if (this.intervalObj[key]) {
          clearInterval(this.intervalObj[key])
        }
      }
      irrigationApi.task(this.defaultFacilityNO).then(res => {
        let data = res.data
        if (data.taskId) {
          this.showTaskBtn = true
          // 控制状态
          let list = []
          data.groups.groups.map(el => {
            list = list.concat(el.dataItems)
          })
          list.map(el => {
            if (data.start && data.start.map(el => { return el.dataItemId }).includes(el.dataItemId)) {
              let row = data.start.find(ele => { return ele.dataItemId == el.dataItemId })
              el.status = row.msg
              // 执行中进度条
              this.intervalObj[dataItemId] && clearInterval(this.intervalObj[dataItemId])
              let dataItemId = el.dataItemId
              let percentage = (row.totalTime || 0) * 1.6 / 1000
              this.intervalObj[dataItemId] = setInterval(() => {
                percentage = percentage + 1.6
                if (percentage >= 100) {
                  percentage = 100
                  if (this.intervalObj[dataItemId]) {
                    clearInterval(this.intervalObj[dataItemId])
                  }
                }
                this.$set(this.percentageObj, dataItemId, percentage)
              }, 1000)
            } else {
              el.status = '待执行'
            }
            if (data.success.includes(el.dataItemId)) {
              el.controled = true
              el.msg = '控制成功'
            }
            if (data.fail.includes(el.dataItemId)) {
              el.controled = true
              el.msg = '控制失败'
            }
            if (data.sync.includes(el.dataItemId)) {
              el.controled = true
              el.msg = '设备同步中，2分内完成'
            }
          })
          this.scheduleList = list
          // 进度
          this.taskId = data.taskId
          this.percentage = 0
          this.co = (data.fail.length || 0) + (data.success.length || 0)
          this.total = this.scheduleList.length || 1
          let percentage = (this.co / this.total * 100).toFixed(1)
          percentage > 100 && (percentage = 100)
          this.percentage = Number(percentage)
        } else {
          this.percentage = 0
          this.showTaskBtn = false
          this.scheduleList = []
        }
      });
    },
    showTask () {
      this.dialogVisible = true
    },
    // 地图
    toggleMap () {
      this.showMap = !this.showMap
    },
    infoMultipleOpen (e) {
      // this.mapFacilityName = e[0].title.facilityName
      // this.showMapControl = true
      // irrigationApi.queryByFacilityNo(e[0].title.facilityNo).then(res => {
      //   this.mapOperationList = res.data.groups;
      //   this.groupObj[this.defaultFacilityNO] = [...this.tableData.groups]
      //   let dataItemIdList = ''
      //   res.data.groups.map(el => {
      //     el.dataItems && el.dataItems.map(ele => {
      //       dataItemIdList += ele.dataItemId + ','
      //     })
      //   })
      //   dataItemIdList = dataItemIdList.substring(0, dataItemIdList.length - 1)
      //   this.queryListById(this.mapOperationList, dataItemIdList)
      // });

      let index = this.facilityList.findIndex(el => { return el.facilityNo == e[0].title.facilityNo })
      index != -1 && this.viewFacility(this.facilityList[index], index)
      this.showMap = false
    },
    backMap () {
      this.showMapControl = false
    },
    // 查询所有设施信息
    async FacilityPointList() {
      const { data: resp } = await divideInfoManage.queryAllFacilityDetail();
      this.groupLngLatArr = [];
      let list = [];
      list = resp;
      this.facilityArr = resp;
      let lngLatAll = [];
      list.forEach((itemthree) => {
        if (itemthree.facilityPointList) {
          let lngLatArr = [];
          let facilityGroupArr = itemthree.facilityPointList;
          facilityGroupArr.forEach((item) => {
            const obj = {};
            obj["lng"] = item.axisY;
            obj["lat"] = item.axisX;
            obj["title"] = itemthree;
            lngLatArr.push(obj);
            lngLatAll.push(obj);
          });
          this.groupLngLatArr.push(lngLatArr);
          this.groupLngLatArr.forEach((item) => {
            item["center"] = this.getCenterPoint(item);
          });
        }
      });
      let center = this.getCenterPoint(lngLatAll);
      if (lngLatAll.length) {
        this.$nextTick(() => {
          this.center = {
            lng: center.lng || 120.230648,
            lat: center.lat || 30.811543
          };
          if (this.groupLngLatArr.length >= 100) {
            this.zoom = 16;
            this.labelStyle.fontSize = "12px";
          } else if (
            this.groupLngLatArr.length >= 60 &&
            this.groupLngLatArr.length < 100
          ) {
            this.zoom = 17;
            this.labelStyle.fontSize = "12px";
          } else if (
            this.groupLngLatArr.length >= 15 &&
            this.groupLngLatArr.length < 60
          ) {
            this.zoom = 18;
            this.labelStyle.fontSize = "14px";
            this.labelStyle.transform = "translateX(-15%)";
          } else if (this.groupLngLatArr.length < 15) {
            this.zoom = 18;
            this.labelStyle.fontSize = "16px";
            this.labelStyle.transform = "translateX(0%)";
          }
        });
      } else {
        const { data: onInfo } =
          await divideInfoManage.queryonInfoByCondition();
        if (onInfo) {
          this.$set(this.center, "lng", onInfo.longitude);
          this.$set(this.center, "lat", onInfo.latitude);
        }
      }
    },
    // 计算多边形中心点
    getCenterPoint(data) {
      let lng = 0.0;
      let lat = 0.0;
      for (let point of data) {
        lat += JSON.parse(point["lat"]);
        lng += JSON.parse(point["lng"]);
      }
      lng = lng / data.length + 0.000084;
      lat = lat / data.length + 0.000014;
      return { lng: lng, lat: lat };
    },
    // 获取开启关闭数量
    loadNum() {
      irrigationApi.countByFacilityNo(this.defaultFacilityNO).then(res => {
        if (res.code == 1) {
          this.numObj = {
            openTotal: res.data.total[0] ? res.data.total[0].dataCollect[1] : 0,
            closeTotal: res.data.total[0] ? res.data.total[0].dataCollect[0] : 0,
            open: res.data.facility[0] ? res.data.facility[0].dataCollect[1] : 0,
            close: res.data.facility[0] ? res.data.facility[0].dataCollect[0] : 0,
          }
        } else {
          this.numObj = {}
        }
      });
    },
    // 查询开启关闭具体蝶阀
    toControlOper (operation, total) {
      let param = {
        operation
      }
      if (total) {
        param.facilityNo = this.defaultFacilityNO
      }
      this.operationList = []
      this.showControl = false
      irrigationApi.queryByOperation(param).then(res => {
        this.operFacilityName = total ? this.facilityName : ''
        if (res.code == 1) {
          this.operationList = res.data
          // 查询状态
          let dataItemIdOperList = ''
          this.operationList.map(el => {
            dataItemIdOperList += el.dataItemId + ','
          })
          dataItemIdOperList = dataItemIdOperList.substring(0, dataItemIdOperList.length - 1)
          this.dataItemIdOperList = dataItemIdOperList
          this.queryOperListById()
        }
      })
    },
    // 查询设施状态
    queryOperListById () {
      irrigationApi.queryListById(this.dataItemIdOperList).then(res => {
        this.operationList.map((ele, index) => {
          let row = res.data.find(item => { return ele.dataItemId == item.dataItemId })
          if (row) {
            let value = row.lastValue1
            if (value == 0) {
              this.$set(this.operationList[index], "nowstau", "已关闭");
            } else if (value == 1) {
              this.$set(this.operationList[index], "nowstau", "已开启");
            } else if (value) {
              this.$set(this.operationList[index], "nowstau", "执行中");
            }
          }
        })
      })
    },
    back () {
      this.showControl = true
    },
    //获取设施组数据
    getfacilityList () {
      this.facilityList = []
      facilityApi.queryFGByFtNo({}).then(res => {
        let list = res.data
        let listone = list.facilityGroupList || []
        let list1 = []
        listone.map(el => {
          list1 = list1.concat(el.facilityList)
        })
        // 未分组设施
        let listtwo = list.facilityList
        this.facilityList = list1.concat(listtwo)
        this.viewFacility(this.facilityList[0], 0)
      });
    },
    viewFacility (data) {
      this.checkGroupList = []
      this.defaultFacilityNO = data.facilityNo
      this.facilityName = data.facilityName
      this.loadNum()
      this.loadTask()
      this.getTableDataList();
    },
    checkMode (i) {
      this.selectIndex = i
    },
    // 获取表格数据
    getTableDataList () {
      this.loading = true
      irrigationApi.queryByFacilityNo(this.defaultFacilityNO).then(res => {
        this.tableData = res.data;
        this.groupObj[this.defaultFacilityNO] = [...this.tableData.groups]
        let dataItemIdList = ''
        res.data.groups.map(el => {
          el.dataItems && el.dataItems.map(ele => {
            dataItemIdList += ele.dataItemId + ','
          })
        })
        dataItemIdList = dataItemIdList.substring(0, dataItemIdList.length - 1)
        this.queryListById(this.tableData.groups, dataItemIdList)
        this.loading = false
      });
    },
    // 查询设施状态
    queryListById (dataList, idList) {
      irrigationApi.queryListById(idList).then(res => {
        dataList.map((el, i) => {
          el.dataItems && el.dataItems.map((ele, index) => {
            let row = res.data.find(item => { return ele.dataItemId == item.dataItemId })
            if (row) {
              let value = row.lastValue1
              if (value == 0) {
                this.$set(dataList[i].dataItems[index], "nowstau", "已关闭");
              } else if (value == 1) {
                this.$set(dataList[i].dataItems[index], "nowstau", "已开启");
              } else if (value) {
                this.$set(dataList[i].dataItems[index], "nowstau", "执行中");
              }
            }
          })
        })
      })
    },
    // 获取机器状态,返回不同颜色
    getequipmentStyle(nowstau) {
      if (nowstau == "已关闭") {
        return "#ff0000";
      }
      if (nowstau == "已开启") {
        return "#00ff33";
      }
      if (nowstau == "执行中") {
        return "#00b6ff";
      }
    },
    // 批量控制
    controlEqupmentBatch (key) {
      if (!this.checkGroupList.length) {
        this.$message.warning("请选择分组")
        return
      }
      this.nowcontrolmessage = {
        zhkey: key,
        checkGroupList: [...this.checkGroupList],
      };
      this.openyanzhencode();
    },
    // 存储数据并且弹出验证码弹框
    controlEqupmentGroup(key, groupNo) {
      this.nowcontrolmessage = {
        zhkey: key,
        groupNo,
      };
      this.openyanzhencode();
    },
    openCode (param) {
      this.controlequpmentone(param.zhid, param.zhkey)
    },
    // 存储数据并且弹出验证码弹框
    controlequpmentone(id, key, facilityNo) {
      this.nowcontrolmessage = {
        zhid: id,
        zhkey: key,
        facilityNo,
      };
      this.openyanzhencode();
    },
    // 打开验证码弹框-重新获取验证码
    openyanzhencode() {
      this.inputCode = "";
      this.yanzhengcodeview = true;
      // 获取随机的验证码和图片
      irrigationApi.getcodeimg().then(res => {
        let { data } = res
        if (data) {
          this.nowcode = data.stringCode;
          this.nowcodeimg = "data:image/png;base64," + data.pictureData;
        }
      });
    },
    // 点击确认按钮
    yanzhengcode() {
      if (this.inputCode === this.nowcode) {
        this.yanzhengcodeview = false;
        this.controlequpment();
      } else {
        this.$message.error("请输入正确的验证码");
      }
    },
    // 控制机器开关状态-------不可轻易调用
    controlequpment () {
      if (
        this.nowcontrolmessage.facilityNo
        || this.nowcontrolmessage.groupNo
        || this.nowcontrolmessage.checkGroupList
      ) {
        this.showTaskBtn = true
        let params = {
          facilityNo: this.defaultFacilityNO,
          controlParam: {
            operation: parseInt(this.nowcontrolmessage.zhkey)
          }
        };
        this.scheduleList = []
        if (this.nowcontrolmessage.groupNo) {
          params.groupNo = this.nowcontrolmessage.groupNo
          let row = this.tableData.groups.find(el => { return el.groupNo == params.groupNo })
          row && (this.scheduleList = [...row.dataItems])
        }
        if (this.nowcontrolmessage.facilityNo) {
          params.facilityNo = this.nowcontrolmessage.facilityNo
          let list = []
          this.tableData.groups.map(el => {
            list = list.concat(el.dataItems)
          })
          this.scheduleList = [...list]
        }
        if (this.nowcontrolmessage.checkGroupList) {
          params.groupNos = this.nowcontrolmessage.checkGroupList
          let list = []
          // for (let key in this.groupObj) {
          //   this.groupObj[key].map(el => {
          //     if (params.groupNos.includes(el.groupNo)) {
          //       list = list.concat(el.dataItems)
          //     }
          //   })
          // }
          this.groupObj[params.facilityNo].map(el => {
            if (params.groupNos.includes(el.groupNo)) {
              list = list.concat(el.dataItems)
            }
          })
          this.scheduleList = [...list]
        }
        // this.total = this.scheduleList.length
        irrigationApi.remoteControl(params).then(res => {
          // 返回值需要确认下
          if (res.code == 1) {
            if (res.data.flag) {
              this.$message.success("控制任务成功!");
              this.taskId = res.data.taskId
              this.showScheduleClose = false
              this.dialogVisible = true
              this.percentage = 0
              this.co = 0
              this.total = res.data.total || 1
              
              // // 准备中进度条
              // this.scheduleList.map((el, i) => {
              //   this.intervalObj[el.dataItemId] = setInterval(() => {
              //     let percentage = (this.percentageObj[el.dataItemId] || 0) + 2
              //     if (percentage >= 100) {
              //       percentage = 100
              //       if (this.intervalObj[el.dataItemId]) {
              //         clearInterval(this.intervalObj[el.dataItemId])
              //       }
              //     }
              //     this.$set(this.percentageObj, el.dataItemId, percentage)
              //   }, 1000)
              // })
            } else {
              this.$message.warning("已有控制任务，请等待完成!");
            }
          } else {
            this.$message.warning(res.msg);
          }
        });
      } else {
        let params = {
          dataItemId: this.nowcontrolmessage.zhid,
          operation: parseInt(this.nowcontrolmessage.zhkey)
        };
        irrigationApi.setshebeikiaguanstau(params).then(res => {
          // 返回值需要确认下
          if (res.code == 1) {
            this.$message.success("控制成功!");
          } else {
            this.$message.warning(res.msg);
          }
        });
        // 点击开关刷新状态,加五秒延迟
        setTimeout(() => {
          this.getTableDataList();
        }, 5000);
      }
    },
    handeltwo (str) {
      if (!str) return []
      let controlslist = [];
      let arr = str.split(";");
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].length > 0) {
          let diy = arr[i].split(":");
          controlslist.push({
            name: diy[1],
            value: diy[0]
          });
        }
      }
      return controlslist;
    },
    // WebSocket
    init() {
      if (typeof WebSocket == "undefined") {
        this.$message.warning("您的浏览器不支持WebSocket");
      } else {
        //服务器地址
        let url = this.$baseurl.webServiceUrl.split('://')[1]
        let socketUrl = `wss://${url}iot-ws/notice`;
        // 开启一个websocket服务
        this.ws = new WebSocket(socketUrl);
        // 打开事件
        this.ws.onopen = () => {
          // 服务器连接成功
          console.log("websocket已打开");
          const params = {
            type: 1,
            data: {
              accesstoken: getToken("token"),
            }
          };
          this.ws.send(JSON.stringify(params));
          this.heartbeatCheck();
        };
        // 浏览器端收消息，获得从服务端发送过来的文本消息
        this.ws.onmessage = msg => {
          //解析信息
          let params = JSON.parse(msg.data);
          if (params.type == 500) {
            this.$message.warning(params.data.content);
          }
          if (params.type == 101 && this.taskId == params.data.taskId) {
            if ([0, 1].includes(params.data.remoteControlType)) {
              this.co++
              let percentage = (this.co / this.total * 100).toFixed(1)
              percentage > 100 && (percentage = 100)
              this.percentage = Number(percentage)
              // 完成的设备
              let dataItemId = params.data.dataItemId
              let index = this.scheduleList.findIndex(el => { return el.dataItemId == dataItemId })
              if (index != -1) {
                this.$set(this.scheduleList[index], "controled", true)
                this.$set(this.scheduleList[index], "msg", params.data.remoteControlType == 0 ? "控制成功" : "控制失败")
              }
              // 更新列表设备状态
              this.getTableDataList()
            }
            if (params.data.remoteControlType == 5) {
              if (params.data.groupNo) {
                for (let key in this.groupObj) {
                  let row = this.groupObj[key].find(el => { return el.groupNo == params.data.groupNo })
                  row && row.dataItems.map(ele => {
                    let index = this.scheduleList.findIndex(el => { return el.dataItemId == ele.dataItemId })
                    if (index != -1) {
                      this.$set(this.scheduleList[index], "status", "待执行")
                    }
                  })
                }
              }
              // 下发任务的设备
              let dataItemId = params.data.dataItemId
              let index = this.scheduleList.findIndex(el => { return el.dataItemId == dataItemId })
              if (index != -1) {
                this.$set(this.scheduleList[index], "status", params.data.content)
                // 开始执行时重新计时
                this.intervalObj[dataItemId] && clearInterval(this.intervalObj[dataItemId])
                // 执行中进度条
                this.intervalObj[dataItemId] = setInterval(() => {
                  let percentage = (this.percentageObj[dataItemId] || 0) + 1.6
                  if (percentage >= 100) {
                    percentage = 100
                    if (this.intervalObj[dataItemId]) {
                      clearInterval(this.intervalObj[dataItemId])
                    }
                  }
                  this.$set(this.percentageObj, dataItemId, percentage)
                }, 1000)
                // 结束计时器
                // this.$set(this.percentageObj, dataItemId, 100)
                // if (this.intervalObj[dataItemId]) {
                //   clearInterval(this.intervalObj[dataItemId])
                // }
              }
            }
            if (params.data.remoteControlType == 7) {
              if (params.data.groupNo) {
                for (let key in this.groupObj) {
                  let row = this.groupObj[key].find(el => { return el.groupNo == params.data.groupNo })
                  row && row.dataItems.map(ele => {
                    let index = this.scheduleList.findIndex(el => { return el.dataItemId == ele.dataItemId })
                    if (index != -1) {
                      // this.$set(this.scheduleList[index], "status", "执行失败")
                      this.$set(this.scheduleList[index], "controled", true)
                      this.$set(this.scheduleList[index], "msg", "执行失败")
                    }
                  })
                }
              }
            }
            if ([3, 4].includes(params.data.remoteControlType)) {
              // 重试
              let dataItemId = params.data.dataItemId
              let index = this.scheduleList.findIndex(el => { return el.dataItemId == dataItemId })
              if (index != -1) {
                this.$set(this.scheduleList[index], "status", params.data.content)
                // 验证中进度条
                this.intervalObj[dataItemId] && clearInterval(this.intervalObj[dataItemId])
                let percentage = 0
                this.intervalObj[dataItemId] = setInterval(() => {
                  percentage = percentage + 1.6
                  if (percentage >= 100) {
                    percentage = 100
                    if (this.intervalObj[dataItemId]) {
                      clearInterval(this.intervalObj[dataItemId])
                    }
                  }
                  this.$set(this.percentageObj, dataItemId, percentage)
                }, 1000)
              }
            }
            if ([8, 9].includes(params.data.remoteControlType)) {
              let dataItemId = params.data.dataItemId
              let index = this.scheduleList.findIndex(el => { return el.dataItemId == dataItemId })
              if (index != -1) {
                this.$set(this.scheduleList[index], "controled", true)
                this.$set(this.scheduleList[index], "msg", params.data.content)
              }
            }
            if (params.data.remoteControlType == 999) {
              this.showScheduleClose = true
            }
          }
        };
        //关闭事件
        this.ws.onclose = () => {
          // 服务器连接关闭
          console.log("websocket已关闭");
          if (!this.close) {
            this.reconnectWebSocket();
          }
        };
        //发生了错误事件
        this.ws.onerror = () => {
          //服务器连接出错
          console.log("websocket发生了错误");
          if (!this.close) {
            this.reconnectWebSocket();
          }
        };
      }
    },
    reconnectWebSocket() {
      this.init(); // 创建新的连接
    },
    // 开启心跳检测
    heartbeatCheck() {
      this.heartbeatTimer && clearInterval(this.heartbeatTimer);
      this.heartbeatTimer = setInterval(() => {
        this.ws.send(JSON.stringify("ping"));
      }, 20 * 1000);
    },
  },
  beforeDestroy() {
    this.close = true;
    this.ws && this.ws.close(); // 关闭当前连接
    this.heartbeatTimer && clearInterval(this.heartbeatTimer);

    for (let key in this.intervalObj) {
      if (this.intervalObj[key]) {
        clearInterval(this.intervalObj[key])
      }
    }
  },
};
</script>

<style scoped lang="scss">
@import "~@/styles/variables.scss";

.irrigation-box {
  width: 100%;
  height: 100%;
  overflow: hidden auto;
  padding: 10px 15px;
  .toggle-box {
    text-align: right;
    height: 40px;
    position: relative;
    .toggle-btn {
      background: linear-gradient(to bottom, #00C4B5, #0097C4);
      padding: 6px 15px;
      width: fit-content;
      border-radius: 15px;
      position: absolute;
      right: 10px;
      cursor: pointer;
    }
  }
  .control-head {
    .control-data {
      display: flex;
      margin-bottom: 15px;
      .data-one {
        font-size: 16px;
        width: 25%;
        height: 105px;
        line-height: 50px;
        text-align: center;
        background: url("~@/assets/environment-data/top-bg.png") no-repeat 100% 100%;
        background-size: cover;
        border-radius: 10px;
        margin-right: 15px;
        cursor: pointer;
        &:last-child {
          margin-right: 0;
        }
        div {
          height: 50%;
          &.num-title {
            border-bottom: 1px solid #2174C7;
          }
          &.num {
            font-size: 30px;
            border-top: 1px solid #66B0F6;
          }
        }
      }
    }
    .area-mode {
      background: #025569;
      padding: 10px 20px 0;
      margin-bottom: 15px;
    }
    .control-area {
      display: flex;
      margin-bottom: 10px;
      .label {
        width: 130px;
        line-height: 30px;
      }
      .control-content {
        width: calc(100% - 130px);
        white-space: nowrap;
        overflow: auto hidden;
        .area-one {
          display: inline-block;
          height: 30px;
          line-height: 30px;
          padding: 0 15px;
          border-radius: 5px;
          text-align: center;
          // border: 1px solid #1093b6;
          cursor: pointer;
          margin-right: 15px;
          background: #0D4758;
          &.active {
            background: #2CD4C5;
            color: #000;
          }
        }
      }
    }
    .control-mode {
      display: flex;
      .label {
        width: 130px;
        line-height: 30px;
      }
      .mode-content {
        width: calc(100% - 130px);
        white-space: nowrap;
        overflow: auto hidden;
        .mode-one {
          display: inline-block;
          height: 30px;
          line-height: 30px;
          padding: 0 15px;
          border-radius: 5px;
          text-align: center;
          // border: 1px solid #1093b6;
          cursor: pointer;
          margin: 0 15px 10px 0;
          background: #0D4758;
          &.active {
            background: #2CD4C5;
            color: #000;
          }
        }
      }
    }
  }
  .tr-sid {
    min-width: 200px;
    width: calc(20% - 15px);
    margin-left: 10px;
    margin-right: 5px;
    height: 100%;
    padding: 0 10px 10px;
    background-color: #00485a;
    .sid-head {
      width: 100%;
      height: 40px;
      line-height: 40px;
      font-size: 18px;
      text-align: center;
      border-bottom: #fff dashed 1px;
    }
    .sid-tree {
      width: 100%;
      height: calc(100% - 40px);
    }
  }
  .right {
    width: 100%;
    height: calc(100% - 270px);
    overflow: hidden auto;
    // 控制开关
    .contro-two-zcon {
      display: inline-block;
      margin-right: 30px;
      height: 30px;
      min-width: 100px;
      line-height: 28px;
      text-align: center;
      font-size: 16px;
      border-radius: 15px;
      cursor: pointer;
      background: #0DD4C5;
      color: #000;
      &.close {
        background: #004758;
        color: #fff;
      }
    }
    .inputnumber {
      width: 100px;
      border-radius: 10rpx;
    }
    .unit {
      position: absolute;
      top: 15px;
      left: 95px;
    }
  }
  .irrigation-one {
    width: 100%;
    height: 100%;
    background-color: #003A48;
    border: 1px solid #005A72;
    .irrigation-title {
      height: 50px;
      font-size: 16px;
      font-weight: bold;
      padding:  10px;
      background: #025569;
      position: relative;
      .group-btn {
        display: inline-block;
        // margin-left: 80px;
        .btn-one {
          display: inline-block;
          margin-right: 50px;
          &:last-child {
            margin-right: 0;
          }
        }
      }
      .task-btn {
        background: linear-gradient(to bottom, #00C4B5, #0097C4);
        padding: 6px 15px;
        width: fit-content;
        border-radius: 15px;
        position: absolute;
        top: 10px;
        right: 15px;
        cursor: pointer;
      }
    }
    .content {
      padding: 10px;
      height: calc(100% - 52px);
      overflow: hidden auto;
      .group {
        display: inline-block;
        width: calc(33% - 10px);
        margin: 0 15px 15px 0;
        padding: 15px 0 0 15px;
        background: #003E4D;
        box-shadow: inset 0 0 6px 1px #FFFFFF16;
        &:nth-child(3n) {
          margin-right: 0;
        }
        .group-title {
          font-size: 16px;
          margin-bottom: 10px;
          ::v-deep {
            .el-checkbox__label {
              color: #fff;
            }
            .el-checkbox__inner {
              background: transparent !important;
              border-radius: 50%;
            }
          }
        }
        .all-control {
          display: inline-block;
          width: 120px;
          height: 100px;
          margin-right: 15px;
          vertical-align: top;
          padding-top: 15px;
          .contro-two-zcon {
            margin: 0 0 15px 0;
            &:last-child {
              margin-bottom: 0;
            }
          }
        }
        .control-box {
          display: inline-block;
          width: 100%;
          min-height: 100px;
          height: fit-content;
        }
      }
      .zh-contro {
        display: inline-block;
        width: calc(33% - 15px);
        height: 90px;
        margin: 0 15px 15px 0;
        background: #025569;
        text-align: center;
        .contro-one {
          display: inline-block;
          width: 100%;
          padding: 10px;
          .contro-one-title {
            font-size: 16px;
            width: 100%;
            height: 36px;
            margin-bottom: 5px;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
          }
          .contro-one-stau {
            font-size: 17px;
          }
        }
        .contro-two {
          display: inline-block;
          width: 80px;
          position: relative;
          .contro-two-zcon:first-child {
            margin-bottom: 8px;
          }
        }
      }
      .nodata {
        text-align: center;
        padding: 5px;
      }
    }
    &.single {
      .content {
        height: 100%;
        .group {
          display: block;
          width: 100%;
          .zh-contro {
            width: 300px;
            height: 120px;
            text-align: left;
            .contro-one {
              display: flex;
              padding-top: 20px;
              .contro-one-title {
                width: calc(100% - 80px);
              }
              .contro-one-stau {
                width: 80px;
              }
            }
            .contro-two {
              width: 100%;
              padding-left: 35px;
            }
          }
        }
      }
    }
  }
}
::v-deep .yanzheng {
  .el-dialog__body {
    padding-left: 50px !important;
  }
  .dig-yanzhencode {
    text-align: center;
    .changecodeimg {
      margin: 10px 0;
      cursor: pointer;
      &:hover {
        color: rgb(26, 170, 175);
      }
    }
  }
  .el-dialog {
    min-width: 500px !important;
  }
}
::v-deep .scheduleForm {
  margin-left: 0 !important;
  width: 100% !important;
  .el-loading-spinner {
    margin-top: -13px;
    .circular {
      width: 25px;
      height: 25px;
    }
  }
  .el-dialog__body {
    padding: 30px 30px 30px 40px !important;
  }
  .schedule {
    height: 400px;
    .progress-box {
      width: 100%;
      text-align: center;
      .progress {
        display: inline-block;
        width: calc(100% - 120px);
        .el-progress-bar {
          border: 1px solid #1A6F8E;
          padding: 3px;
          border-radius: 10px;
          width: calc(100% - 60px);
          margin-right: 0;
        }
      }
    }
    .content {
      height: calc(100% - 30px);
      margin-top: 20px;
      overflow: hidden auto;
      .schedule-one {
        display: inline-block;
        margin: 0 15px 15px 0;
        width: calc(33% - 10px);
        height: 100px;
        padding: 5px;
        // border-radius: 5px;
        // border: 1px solid #1093b6;
        background: #1B6E91;
        vertical-align: top;
        text-align: center;
        color: #fff;
        font-size: 16px;
        &:nth-child(3n) {
          margin-right: 0;
        }
        .line {
          padding: 6px 0;
        }
        .msg {
          color: #f8c300;
        }
        .green {
          color: #2CD4C5;
        }
        .red {
          color: red
        }
      }
    }
  }
}
.map-box {
  width: 100%;
  height: 100%;
  padding: 10px 15px;
  .toggle-box {
    text-align: right;
    height: 40px;
    position: relative;
    .toggle-btn {
      background: linear-gradient(to bottom, #00C4B5, #0097C4);
      padding: 6px 15px;
      width: fit-content;
      border-radius: 15px;
      position: absolute;
      right: 10px;
      cursor: pointer;
    }
  }
  .map {
    width: 100%;
    height: 100%;
  }
  ::v-deep {
    .anchorBL,
    .BMap_cpyCtrl {
      display: none;
    }
    .BMap_Marker {
      div {
        display: none;
      }
    }
    .BMap_noprint {
      display: block;
    }
  }
}
</style>
